package whx.handler.mapping.impl;

import org.springframework.beans.BeansException;
import org.springframework.stereotype.Component;
import whx.annotation.RequestMapping;
import whx.handler.mapping.HandlerMapping;
import whx.springmvc.RequestMappingInfo;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Component
public class AnnotationHandlerMapping implements HandlerMapping {

    static Map<String,Object> map = new HashMap<>();
    @Override
    public Object getHandler(String url) {
        return map.get(url);
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        Method[] methods = bean.getClass().getDeclaredMethods();
        for(Method m : methods){
            RequestMappingInfo info = this.createRequestInfo(m,bean);
            map.put(info.getUrl(),info);
        }
        return true;
    }
    //定义一个对象，需要知道bean本身 和 Method
    private RequestMappingInfo createRequestInfo(Method method, Object object){
        RequestMappingInfo info = new RequestMappingInfo();
        if(method.isAnnotationPresent(RequestMapping.class)){
            info.setMethod(method);
            info.setObject(object);
            info.setUrl(method.getDeclaredAnnotation(RequestMapping.class).value());
        }
        return info;
    }
}
